#! /bin/bash

## expath-pkg-install --... (TODO:)
##
## Install a package in EXPath Packaging format into a repository for
## Saxon.
##
## Depends on the following environment variables: (TODO:)
##
##   - EXPATH_REPO
##
## Use mktemp(1) to create a temporary directory (which in turn uses
## environment variables.)

# expath-pkg.xml
# saxon8/http-client-0.3/catalog.xml
# saxon8/http-client-0.3/jar/expath-http-client-saxon8.jar
# saxon8/http-client-0.3/xsl/expath-http-client-saxon8.xsl
#
# <package xmlns="http://expath.org/mod/expath-pkg">
#    <module version="0.3" name="expath-http-client">
#       <title>EXPath HTTP Client</title>
#    </module>
# </package>


# Functions

function die() {
    echo Error: "$*";
    exit 1;
}

# Preconditions

if [[ -z "${EXPATH_REPO}" ]]; then
    die EXPATH_REPO is not set
fi

# TODO: read options

# a) unzip in temp dir

TMP_DIR=`mktemp -d -t expath-pkg`
if [[ -z "${TMP_DIR}" ]]; then
    die "Unable to get a temporary directory";
fi
unzip "$1" -d "$TMP_DIR" >/dev/null 2>&1 || die "Error unziping the package"
echo "Package unziped to $TMP_DIR"

# b) read the descriptor

# c) choose the generic and saxon8 parts (ask for confirm)

# TODO: Problem with the condition, check that and fix the problem, I
# must do the check.
if test \( ! -d "${TMP_DIR}/saxon8" \) -a \( ! -d "${TMP_DIR}/generic" \); then
    die "There is no implementation found in the package (for saxon8 and generic.)";
fi

for impl in "${TMP_DIR}"/{generic,saxon8}; do
    impl_base=`basename ${impl}`
    for mod in "${impl}"/*; do
        mod_base=`basename ${mod}`
        if [[ -d "${mod}" ]]; then
            read -p "Install module ${mod_base} for ${impl_base}? [Y/n]: " resp;
            if test "${resp}" = y -o "${resp}" = Y -o -z "${resp}"; then
                echo cp -R "${mod}" "${EXPATH_REPO}/${impl_base}";
            fi
        fi
    done
done

# d) ask for confirm for the name of the module (so possible to easily
#    install different versions by giving them different names)

# e) ask for confim for each dep that can be installed auto

# f) display a msg about deps to install manually
